package edu.zut.software.identity.Service.impl;

import edu.zut.software.identity.Repository.StuCollegeRepository;

import edu.zut.software.identity.Service.StuCollegeService;
import edu.zut.software.identity.domain.StuCollege;
import edu.zut.software.identity.domain.StuGrade;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;

@Service
public class StuCollegeServiceImpl implements StuCollegeService {

    private StuCollegeRepository stuCollegeRepository;

    @Autowired
    public void setStuCollegeRepository(StuCollegeRepository stuCollegeRepository) {
        this.stuCollegeRepository = stuCollegeRepository;
    }

    @Override
    public StuCollege findById(String id) {

        return stuCollegeRepository.findById(id).orElseThrow(RuntimeException::new);
    }

    @Override
    public List<StuCollege> findAll() {
        return stuCollegeRepository.findAll();
    }

    @Override
    public void deleteById(String id) {
        stuCollegeRepository.deleteById(id);
    }

    @Override
    public void save(StuCollege stuCollege) {
        stuCollegeRepository.save(stuCollege);
    }

    @Override
    public Page<StuCollege> findAll(Integer page, Integer pageSize) {
        Pageable pageable = PageRequest.of(page, pageSize);
        Page<StuCollege> pageInfo = stuCollegeRepository.findAll(pageable);
        return pageInfo;
    }

    @Override
    public Page<StuCollege> findAll(Integer page, Integer pageSize, String name) {

        Pageable pageable = PageRequest.of(page, pageSize);
        Page<StuCollege> jzgPage = stuCollegeRepository.findAll(new Specification<StuCollege>(){

            @Override
            public Predicate toPredicate(Root<StuCollege> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<Predicate> list = new ArrayList<>();
                if(null != name && name != ""){
                    list.add(criteriaBuilder.like(root.get("college_name").as(String.class), "%" + name + "%"));
                }

                Predicate[] predicates = new Predicate[list.size()];
                return criteriaBuilder.and(list.toArray(predicates));
            }
        }, pageable);

        return jzgPage;
    }
}